package com.example.farmeri.http;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * Create by weiqishan on 2020/3/6.
 */
public class HttpCookieManager implements CookieJar {

    private HashMap<String, HashMap<String, String>> mCookieMap = new HashMap<>(3);
    private static String[] COOKIE_SKIP_KEY = {"domain", "path", "expires", "max-age", "discard"};

    private HttpCookieManager() {}
    private static HttpCookieManager instance = new HttpCookieManager();

    public static HttpCookieManager getInstance() {
        return instance;
    }

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        if (cookies == null) {
            return;
        }
        String host = url.host();
        HashMap<String, String> cookieMap = mCookieMap.get(host);
        if (cookieMap == null) {
            cookieMap = new HashMap<>(5);
        }
        for (Cookie cookie : cookies) {
            String str = cookie.toString();
            String[] attrs = str.split(";");
            for (String attr : attrs) {
                if (attr.contains("=")) {
                    String[] kv = attr.split("=");
                    if (!isSkip(kv[0])) {
                        cookieMap.put(kv[0], kv[1]);
                    }
                }
            }
        }
        mCookieMap.put(host, cookieMap);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> list = new ArrayList<>(1);
        list.add(new Cookie.Builder()
                .name("Cookie")
                .value(getCookieStr(url.uri()))
                .domain(url.host())
                .build());

        return list;
    }

    private boolean isSkip(String key) {
        for (int i = 0; i < COOKIE_SKIP_KEY.length; i++) {
            if (COOKIE_SKIP_KEY[i].equals(key.toLowerCase().trim())) {
                return true;
            }
        }
        return false;
    }

    public String getCookieStr(URI uri) {
        String cookieStr = "";
        HashMap<String, String> cookieMap = mCookieMap.get(uri.getHost());
        if (cookieMap != null) {
            Iterator<Map.Entry<String, String>> it = cookieMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                cookieStr += entry.getKey() + "=" + entry.getValue();
            }
        }
        return cookieStr;
    }
}